package org.yunai.swjg.server.module.rep.callback;

import org.slf4j.Logger;
import org.yunai.swjg.server.core.annotation.MainThread;
import org.yunai.swjg.server.core.service.Online;
import org.yunai.swjg.server.core.service.OnlineContextService;
import org.yunai.swjg.server.module.player.PlayerExitReason;
import org.yunai.swjg.server.module.player.vo.Player;
import org.yunai.swjg.server.module.scene.NormalSceneService;
import org.yunai.swjg.server.module.scene.core.SceneCallable;
import org.yunai.swjg.server.rpc.message.S_C.S_C_RepLeaveResp;
import org.yunai.yfserver.common.LoggerFactory;
import org.yunai.yfserver.spring.BeanManager;

/**
 * 玩家从副本切换到普通场景回调
 * User: yunai
 * Date: 13-5-14
 * Time: 下午7:49
 */
public class PlayerSwitchRepToNormalSceneCallback implements SceneCallable {

    private static final Logger LOGGER = LoggerFactory.getLogger(LoggerFactory.Logger.scene, PlayerSwitchRepToNormalSceneCallback.class);

    private static OnlineContextService onlineContextService;
    private static NormalSceneService normalSceneService;
    static {
        onlineContextService = BeanManager.getBean(OnlineContextService.class);
        normalSceneService = BeanManager.getBean(NormalSceneService.class);
    }

    /**
     * 玩家编号
     */
    private final Integer playerId;

    public PlayerSwitchRepToNormalSceneCallback(Integer playerId) {
        this.playerId = playerId;
    }

    @Override
    @MainThread
    public void call() {
        Online online = onlineContextService.getPlayer(playerId);
        if (online == null) {
            LOGGER.error("[call] [online({}) is not found].", playerId);
            return;
        }
        Player player = online.getPlayer();
        if (player.isScenePreInfoNull()) {
            LOGGER.error("[call] [player({}) scenePreInfo is null].", playerId);
            online.setExitReason(PlayerExitReason.SERVER_ERROR);
            online.disconnect();
            return;
        }
        Integer sceneId = player.getScenePreId();
        Short sceneX = player.getScenePreX();
        Short sceneY = player.getScenePreY();
        online.write(new S_C_RepLeaveResp(sceneId, sceneX, sceneY));
        player.clearScenePreInfo(); // 清理掉上一次场景信息
        normalSceneService.onPlayerEnterNormalScene(online, sceneId, sceneX, sceneY);
    }
}
